local skel = fk.CreateSkill {
  name = "rmt__quni",
}

Fk:loadTranslationTable{
  ["rmt__quni"] = "取逆",
  [":rmt__quni"] = "你造成伤害后，可令一名角色获得以下效果：“当你受到伤害后，你摸一张牌”。若已有，改为：“受到1点伤害后”。",

  ["@rmt__quni"] = "取逆",
  ["rmt_level1"] = "一级",
  ["rmt_level2"] = "二级",
  ["#rmt__quni-choose"] = "取逆：你可以令一名角色获得“受到伤害后摸1牌”的效果",

  ["$rmt__quni1"] = "匹磾囚琨于幽州，吾欲解之，且将此信交予其手。",
  ["$rmt__quni2"] = "典午实亡于永嘉，今南渡苟存，皆赖我王氏之手。",
}

skel:addEffect(fk.Damage, {
  anim_type = "support",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(skel.name) and target == player then
      return table.find(player.room.alive_players, function (p) return p:getMark("@rmt__quni") ~= "rmt_level2" end)
    end
  end,
  on_cost = function (self, event, target, player, data)
    local targets = table.filter(player.room.alive_players, function (p) return p:getMark("@rmt__quni") ~= "rmt_level2" end)
    local tos = player.room:askToChoosePlayers(player, {
      targets = targets,
      max_num = 1, min_num = 1, skill_name = skel.name,
      prompt = "#rmt__quni-choose",
    })
    if #tos > 0 then
      event:setCostData(self, {tos = tos})
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local to = event:getCostData(self).tos[1]
    room:setPlayerMark(to, "@rmt__quni", to:getMark("@rmt__quni") == 0 and "rmt_level1" or "rmt_level2")
  end,
})

skel:addEffect(fk.Damaged, {
  anim_type = "drawcard",
  is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and not player.dead and player:getMark("@rmt__quni") ~= 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    for _ = 1, (player:getMark("@rmt__quni") == "rmt_level2" and data.damage or 1) do
      if player.dead then break end
      player:drawCards(1, skel.name)
    end
  end,
})

skel:addAI({
  think = function(self, ai)
    -- 选出界面上所有可选的目标
    local players = ai:getEnabledTargets()
    -- 对所有目标摸牌的收益
    local benefits = table.map(players, function(p)
      local benefit = ai:getBenefitOfEvents(function(logic) -- 此人摸牌收益
        logic:drawCards(p, 1)
      end)
      if p:getMark("@rmt__quni") ~= 0 then -- 如果我是1级，认为我收益减半
        benefit = benefit * 0.5
      end
      return { p, benefit }
    end)
    -- 选择收益最高的一位
    table.sort(benefits, function(a, b) return a[2] > b[2] end)
    local to, benefit = table.unpack(benefits[1])
    if to == nil or benefit <= 0 then return "" end
    return { targets = {to} }, benefit
  end,
})

return skel
